package com.ruoyi.app.business.project;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.app.business.file.FileBusiness;
import com.ruoyi.app.business.message.MessageBusiness;
import com.ruoyi.app.config.util.UserUtil;
import com.ruoyi.app.converter.ProjectDeliveryConverter;
import com.ruoyi.app.domain.project.ReserveFundDetail;
import com.ruoyi.app.domain.project.delivery.ProjectDelivery;
import com.ruoyi.app.domain.project.verify.ProjectVerify;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.service.company.service.CompanyService;
import com.ruoyi.service.message.enums.MessageTemplateEnum;
import com.ruoyi.service.project.entity.ProjectDeliveryEntity;
import com.ruoyi.service.project.entity.ProjectEntity;
import com.ruoyi.service.project.enums.DeliveryStatusEnum;
import com.ruoyi.service.project.enums.ProjectStatusEnum;
import com.ruoyi.service.project.service.ProjectDeliveryService;
import com.ruoyi.service.project.service.ProjectService;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * <p>
 * 作用：项目相关业务
 * </p>
 *
 * @author Zane
 * @since 2025-10-10 2:19
 */
@Slf4j
@Component
public class ProjectDeliveryBusiness {

  @Resource
  private ProjectDeliveryService projectDeliveryService;
  @Resource
  private ProjectService projectService;
  @Resource
  private MessageBusiness messageBusiness;
  @Resource
  private CompanyService companyService;

  @Resource
  private TransactionTemplate transactionTemplate;
  @Resource
  private ProjectLaborBusiness projectLaborBusiness;
  @Resource
  private ProjectSettleBusiness projectSettleBusiness;
  @Autowired
  private FileBusiness fileBusiness;


  /**
   * 交付
   */
  public void delivery(ProjectDelivery deliveryInfo) {
    // 2025/10/18 交付逻辑:获得项目信息,校验项目状态(交付中),验证登录用户是否是项目leader,转换成实体对象,保存
    final ProjectEntity project = getAndCheckProject(deliveryInfo.getProjectId(),
        ProjectStatusEnum.ON_DELIVERY);
    final Long userId = UserUtil.getUserId();
    if (project.getProjectLeader().compareTo(userId) != 0) {
      throw new ServiceException(
          StringUtils.format("您不是项目[{}]的项目leader,禁止交付项目",
              project.getProjectName()));
    }
    final ProjectDeliveryEntity projectDeliveryEntity = supplement(
        ProjectDeliveryConverter.INSTANCE.info2Entity(deliveryInfo));
    project.setStatus(ProjectStatusEnum.VERIFYING.getCode())
        .setDeliveryTime(LocalDateTime.now())
        .setUpdateTime(LocalDateTime.now())
        .setUpdateBy(UserUtil.getUserId());
    transactionTemplate.executeWithoutResult(status -> {
      projectDeliveryService.save(projectDeliveryEntity);
      projectService.updateById(project);
      messageBusiness.addMessage(MessageTemplateEnum.A4,
          messageBusiness.buildProjectProperties(project), project.getId(),
          project.getCreateBy(), companyService.getNameById(project.getComId()),
          project.getProjectLeader());
    });
  }

  /**
   * 项目验收
   */
  public void verify(ProjectVerify verify) {
    //校验
    if (DeliveryStatusEnum.REJECT.eqCode(verify.getVerifyStatus())
        && StringUtils.isBlank(verify.getVerifyContent())) {
      throw new ServiceException("验收驳回时,验收内容不能为空");
    }
    final ProjectEntity project = getAndCheckProject(verify.getProjectId(),
        ProjectStatusEnum.VERIFYING);
    final Long userId = UserUtil.getUserId();
    if (project.getCreateBy().compareTo(userId) != 0) {
      throw new ServiceException(StringUtils.format("用户{}不是项目{}的创建者,禁止验收项目", userId,
          project.getProjectName()));
    }
    final ProjectDeliveryEntity deliveryInfo = CommonUtils.requireNotNull(
        projectDeliveryService.getUnVerifiedDelivery(verify.getProjectId()),
        "该项目无有效交付记录信息,无法验收");
    deliveryInfo.setVerifyBy(userId)
        .setVerifyTime(LocalDateTime.now())
        .setVerifyStatus(verify.getVerifyStatus())
        .setVerifyContent(verify.getVerifyContent())
        .setCommentScore(verify.getCommentScore())
        .setCommentContent(verify.getCommentContent());
    //判断验收结果
    if (DeliveryStatusEnum.REJECT.eqCode(verify.getVerifyStatus())) {
      //回退交付状态
      project.setStatus(ProjectStatusEnum.ON_DELIVERY.getCode())
          .setUpdateBy(userId)
          .setUpdateTime(LocalDateTime.now());
    } else {
      project.setStatus(ProjectStatusEnum.SETTLING.getCode())
          .setUpdateBy(userId)
          .setUpdateTime(LocalDateTime.now());
    }
    //保存
    transactionTemplate.executeWithoutResult(status -> {
      projectDeliveryService.updateById(deliveryInfo);
      projectService.updateById(project);
      if (DeliveryStatusEnum.PASS.eqCode(verify.getVerifyStatus())) {
        //验收通过 1 生成项目结算单
        projectSettleBusiness.generateSettlement(project, deliveryInfo);
        //验收通过 2 发送评价消息
        //2.1创建方
        messageBusiness.addMessage(MessageTemplateEnum.A5,
            messageBusiness.buildProjectProperties(project), project.getId(),
            project.getCreateBy(), companyService.getNameById(project.getComId()),
            project.getProjectLeader());
        //2.2制作方
        final List<Long> labors = projectLaborBusiness.listHiredUserByProjectId(project.getId());
        if (CollUtil.isNotEmpty(labors)) {
          messageBusiness.addMessage(MessageTemplateEnum.A6,
              messageBusiness.buildProjectProperties(project), project.getId(),
              project.getCreateBy(), companyService.getNameById(project.getComId()),
              project.getProjectLeader());
        }
        //2.3项目leader
        messageBusiness.addMessage(MessageTemplateEnum.A7,
            messageBusiness.buildProjectProperties(project), project.getId(),
            project.getProjectLeader(), companyService.getNameById(project.getComId()),
            project.getProjectLeader());
      }
    });

  }

  private ProjectEntity getAndCheckProject(String projectId, ProjectStatusEnum targetStatus) {
    final ProjectEntity project = CommonUtils.requireNotNull(
        projectService.getById(projectId), "项目ID不存在");
    if (!targetStatus.eqCode(project.getStatus())) {
      //log.warn("项目{}状态不是{},禁止交付项目", targetStatus.getName(), project.getProjectName());
      throw new ServiceException(
          StringUtils.format("项目{}状态不是{},禁止操作", project.getProjectName(),
              targetStatus.getName()));
    }
    return project;
  }

  /**
   * 补充基础信息
   */
  private ProjectDeliveryEntity supplement(ProjectDeliveryEntity entity) {
    //补充预定金使用信息
    if (StringUtils.isNotBlank(entity.getReserveFundUsedFileKey())) {
      final List<ReserveFundDetail> details = fileBusiness.dataListByFileKey(
          entity.getReserveFundUsedFileKey(), ReserveFundDetail.class);
      if (CollUtil.isNotEmpty(details)) {
        entity.setReserveFundUsedAmount(details.stream().map(ReserveFundDetail::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add));
      }
    }

    //补充创建人信息,更新人信息
    entity.setCreateBy(UserUtil.getUserId())
        .setCreateTime(LocalDateTime.now())
        .setUpdateBy(UserUtil.getUserId())
        .setUpdateTime(LocalDateTime.now());
    return entity;
  }


 /* public List<ProjectDeliveryEntity> getNeedSettleList() {
    return projectDeliveryService.getNeedSettleList();
  }*/
}
